package sk.velkavrana.app.ui;

import com.jgoodies.binding.adapter.BasicComponentFactory;
import com.jgoodies.binding.beans.PropertyAdapter;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import sk.velkavrana.app.context.Context;
import sk.velkavrana.app.model.ConnectionInfo;
import sk.velkavrana.app.model.ImportActions;
import sk.velkavrana.app.service.ImportService;
import sk.velkavrana.app.ui.components.JChooserPanel;
import sk.velkavrana.app.ui.components.JImportProgressBarPanel;
import sk.velkavrana.app.util.UIUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;

/**
 * @author mtymes
 * @since May 25, 2009 9:38:34 AM
 */
public class JImportPanel extends JPanel {

    private ImportActions importActions = new ImportActions();

    private JChooserPanel fileChooserPanel;


    private JPanel initActionPanel() {
        FormLayout actionLayout = new FormLayout(
                "4dlu, pref:grow, 4dlu", // columns
                "2dlu, pref, pref, pref, pref, 2dlu" // rows
        );

        JPanel actionPanel = new JPanel(actionLayout);
        actionPanel.setBorder(BorderFactory.createTitledBorder("Actions"));

        CellConstraints cc = new CellConstraints();

        ValueModel dropTableModel = new PropertyAdapter(importActions, "dropTable");
        JCheckBox dropTableCheckBox = BasicComponentFactory.createCheckBox(dropTableModel, "Drop table");
        actionPanel.add(dropTableCheckBox, cc.xy(2, 2));

        ValueModel createTableModel = new PropertyAdapter(importActions, "createTable");
        JCheckBox createTableCheckBox = BasicComponentFactory.createCheckBox(createTableModel, "Create new table");
        actionPanel.add(createTableCheckBox, cc.xy(2, 3));

        ValueModel clearDataModel = new PropertyAdapter(importActions, "clearData");
        JCheckBox clearDataCheckBox = BasicComponentFactory.createCheckBox(clearDataModel, "Clear old data");
        actionPanel.add(clearDataCheckBox, cc.xy(2, 4));

        ValueModel importDataModel = new PropertyAdapter(importActions, "importData");
        JCheckBox importDataCheckBox = BasicComponentFactory.createCheckBox(importDataModel, "Insert new data");
        actionPanel.add(importDataCheckBox, cc.xy(2, 5));

        return actionPanel;
    }


    private JButton initImportButton() {
        return new JButton(new AbstractAction("Process") {
            public void actionPerformed(ActionEvent e) {
                final Set<String> files = fileChooserPanel.getValues();

                if (files.size() == 0) {
                    JOptionPane.showMessageDialog(
                            JImportPanel.this,
                            "No files are selected for import",
                            "Empty selection",
                            JOptionPane.WARNING_MESSAGE
                    );
                } else if (!importActions.isSomeActionSet()) {
                    JOptionPane.showMessageDialog(
                            JImportPanel.this,
                            "No action has been choosen",
                            "Empty selection",
                            JOptionPane.WARNING_MESSAGE
                    );
                } else {
                    Context context = Context.getInstance();
                    final ConnectionInfo connectionInfo = context.getConnectionInfoEx();
                    final String importDirectory = context.getImportDirectory();
                    final ImportService importService = context.getImportService();

                    final JImportProgressBarPanel importProgressBarPanel = new JImportProgressBarPanel();
                    JDialog dialog = new JDialog((Frame) null, "Import files", true);
                    dialog.getContentPane().setLayout(new BorderLayout());
                    dialog.getContentPane().add(importProgressBarPanel);
                    dialog.pack();
                    dialog.setSize(400, dialog.getSize().height);

                    Runnable exportRunnable = new Runnable() {
                        public void run() {
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e1) {
                                e1.printStackTrace();
                            }

                            importService.importData(connectionInfo, importActions, files, importDirectory, importProgressBarPanel.getImportDataListener());
                        }
                    };
                    Thread exportThread = new Thread(exportRunnable);
                    exportThread.start();


                    UIUtil.center(dialog);
                    UIUtil.show(dialog);
                }
            }
        });
    }


    private JButton initCloseButton() {
        return new JButton(new AbstractAction("Close") {
            public void actionPerformed(ActionEvent e) {
                getTopLevelAncestor().setVisible(false);
            }
        });
    }


    private JPanel initButtonPanel() {
        FormLayout buttonLayout = new FormLayout(
                "pref:grow, pref,4dlu, pref, 2dlu", // columns
                "4dlu, pref, 2dlu" // rows
        );

        JPanel buttonPanel = new JPanel(buttonLayout);

        CellConstraints cc = new CellConstraints();

        buttonPanel.add(initImportButton(), cc.xy(2, 2));
        buttonPanel.add(initCloseButton(), cc.xy(4, 2));

        return buttonPanel;
    }


    private void init() {
        Context context = Context.getInstance();
        String importDirectory = context.getImportDirectory();

        File dir = new File(importDirectory);
        Set<String> fileSet = new TreeSet<String>(
                Arrays.asList(
                        dir.list(new FilenameFilter() {
                            public boolean accept(File dir, String name) {
                                String[] tokens = name.split("\\.");

                                return "xml".equalsIgnoreCase(tokens[tokens.length - 1]);
                            }
                        })
                ));

        FormLayout exportLayout = new FormLayout(
                "2dlu, pref:grow, 2dlu", // columns
                "2dlu, default, pref, pref, 4dlu" // rows
        );

        setLayout(exportLayout);

        CellConstraints cc = new CellConstraints();

        fileChooserPanel = new JChooserPanel("Choose files for import: ", fileSet, null);
        add(fileChooserPanel, cc.xy(2, 2));
        add(initActionPanel(), cc.xy(2, 3));
        add(initButtonPanel(), cc.xy(2, 4));
    }


    public JImportPanel(LayoutManager layout, boolean isDoubleBuffered) {
        super(layout, isDoubleBuffered);

        init();
    }


    public JImportPanel(LayoutManager layout) {
        super(layout);

        init();
    }


    public JImportPanel(boolean isDoubleBuffered) {
        super(isDoubleBuffered);

        init();
    }


    public JImportPanel() {
        init();
    }
}
